import { SERVICES_KEY } from '../constants';
/**
 * @description 创建service
 * @param {*} url api url
 * @param {*} options http options
 */
function createService(url, options = {}, http) {
  const { method = 'post' } = options;
  const httpMethod = http[method];
  if (httpMethod) {
    return async function request(params) {
      return httpMethod(url, params, options);
    };
  }
  throw new Error(`method=${method}请求方式不存在`);
}

/**
 * @description 创建http Decorator
 * @param {*} http
 */
export default function createServiceDecorator(http) {
  return function service(url, options, methodHttp) {
    return function desc(target, name, descriptor) {
      const services = target[SERVICES_KEY] || {};
      services[name] = createService(url, options, http || methodHttp);
      /** services key */
      Object.assign(target, { [SERVICES_KEY]: services });

      return descriptor;
    };
  };
}
